<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="<%=request.getContextPath()%>/public/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/public/strophe/strophe.umd.min.js"></script>

<!-- 
<script type="text/javascript" src="<%=request.getContextPath()%>/public/core.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/public/bosh.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/public/md5.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/public/sha1.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/public/utils.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/public/websocket.js"></script>
 -->
<meta charset="UTF-8">
<title>xmpp测试页</title>
</head>
<body>
	用户id，例如test1：<input type="text" id="input-jid">
    <br>
    密码,同用户id：<input type="password" id="input-pwd">
    <br>
    <button id="btn-login">登录</button>
    <br>
    新用户id，例如test1：<input type="text" id="input-newjid">
    <br>
    新用户密码：<input type="password" id="input-newpwd">
    <br>
    <button id="btn-createuser">注册新用户</button>
    <br>
    主题(聊天室，组群)id，例如：meetingroom3：<input type="text" id="input-groupjid">
    <br>
    主题(聊天室，组群)名称，例如：日报的主题3：<input type="text" id="input-groupname">
    <br>
    <button id="btn-joingroup">加入(聊天室，组群)主题</button>
    <button id="btn-creategroup">创建(聊天室，组群)主题</button>
    <button id="btn-getgroupuser">获取(聊天室，组群)主题人员</button>
    <div id="msg" style="height: 400px; width: 100%; overflow: scroll;"></div>
    <br>
    消息：
    <br>
    <textarea id="input-msg" cols="30" rows="4"></textarea>
    <br>
    <button id="btn-send">发送主题消息</button>
    <button id="btn-sendfile">发送主题文件/图片</button>
    <br>
    <br>
    <button id="btn-addgroupuserback">后台初始化组群用户</button>
    <button id="btn-sendgroupmsgback">后台发送组群消息</button>
    <button id="btn-joingroupback">后台加入组群</button>
    <button id="btn-sendusermsgback">后台给登录用户发送消息</button>
    <button id="btn-getmygroup">获取我的组群</button>
    <button id="btn-getmymsgs">获取我的站内信(消息)</button>
    <button id="btn-getbusinessmsgs">获取业务(消息)</button>
    
    <br>
</body>
<script language="javascript">
//XMPP服务器BOSH地址
var BOSH_SERVICE = 'http://yscgc.3322.org:5280/';

var USER_DOMAIN = '@ysyngc.com';

var GROUP_DOMAIN = '@muc.ysyngc.com';

// 房间JID
var ROOM_JID = 'meetingroom2@muc.ysyngc.com';


// XMPP连接
var connection = null;

// 当前状态是否连接
var connected = false;

// 当前登录的JID
var jid = "";

Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "H+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}


// 连接状态改变的事件
function onConnect(status) {
    if (status == Strophe.Status.CONNFAIL) {
        alert("连接失败！");
    } else if (status == Strophe.Status.AUTHFAIL) {
        alert("登录失败！");
    } else if (status == Strophe.Status.DISCONNECTED) {
        alert("连接断开！");
        connected = false;
    } else if (status == Strophe.Status.CONNECTED) {
        alert("连接成功，可以开始聊天了！");
        connected = true;

        // 当接收到<message>节，调用onMessage回调函数
        connection.addHandler(onMessage, null, 'message', null, null, null);

        // 首先要发送一个<presence>给服务器（initial presence）
        connection.send($pres().tree());

        
        //connection.sendIQ(pres);//获取房间列表
    }else if (status == Strophe.Status.ERROR) {
        alert("连接失败2！");
        connected = false;
    }else{
    	alert('unknown status:' + status);
    }
}

// 接收到<message>
function onMessage(msg) {

    console.log(msg);
    // 解析出<message>的from、type属性，以及body子元素
    var from = msg.getAttribute('from');
    var type = msg.getAttribute('type');
    var elems = msg.getElementsByTagName('body');
    var delay = msg.getElementsByTagName('delay');
    var stamp = delay.stamp;

    
    

    if (delay.length < 1) {
    	if (type == "groupchat" && elems.length > 0) {//群消息
            var body = elems[0];
            var stampe = delay[0];
            $("#msg").append(Strophe.getText(stampe) + from.substring(0, from.indexOf('/')) + ":" + from.substring(from.indexOf('/') + 1) + ":<br>" + Strophe.getText(body) + "<br>")
        }else if(type == "chat" && elems.length > 0){ //私聊消息
        	var body = elems[0];
            $("#msg").append((new Date().Format("yyyy-MM-dd/HH:mm:ss")) + from.substring(0, from.indexOf('/')) + ":" + from.substring(from.indexOf('/') + 1) + ":<br>" + Strophe.getText(body) + "<br>")
        }
    } else {
      // console.log(333)
      // console.log(delay)
    }

    
    
    return true;
}

$(document).ready(function() {

    // 通过BOSH连接XMPP服务器
    $('#btn-login').click(function() {
        if(!connected) {
            connection = new Strophe.Connection(BOSH_SERVICE);
            connection.connect($("#input-jid").val() + USER_DOMAIN, $("#input-pwd").val(), onConnect);
            jid = $("#input-jid").val() + USER_DOMAIN;
            //alert('用户id=' + jid);
        }
    });

    // 发送消息
    $("#btn-send").click(function() {
        if(connected) {

            // 创建一个<message>元素并发送
            var msg = $msg({
                to: $("#input-groupjid").val() + GROUP_DOMAIN, 
                from: jid, 
                type: 'groupchat'
            }).c("body", null, $("#input-msg").val());
            connection.send(msg.tree());

            $("#input-msg").val('');
        } else {
            alert("请先登录！");
        }
    });
    
 	// 注册新用户
    $('#btn-createuser').click(function() {
        
    });
 	
 // 进入组群
    $('#btn-joingroup').click(function() {
    	if(connected) {

    		// 发送<presence>元素，加入房间
            var pres1 = $pres({
                from: jid,
                to: $("#input-groupjid").val() + GROUP_DOMAIN + "/" + jid.substring(0,jid.indexOf("@"))
            }).c('x',{xmlns: 'http://jabber.org/protocol/muc'}).tree();
            connection.send(pres1);
        } else {
            alert("请先登录！");
        }
    });
 
  
 
 // 创建主题（组群）
    $('#btn-creategroup').click(function() {
    	//创建iq  input-groupjid
		var iq = $iq({
			to: $("#input-groupjid").val() + GROUP_DOMAIN,  
			type: 'set'
		}).c("query", {
			xmlns: 'http://jabber.org/protocol/muc#owner'
		});
		iq.c("x", {
			xmlns: "jabber:x:data",
			type: "submit"
		});

		//send configuration you want
		//iq.c('field', { 'var': 'FORM_TYPE' }).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
		//iq.c('field', { 'var': 'muc#roomconfig_publicroom' }).c('value').t('1').up().up();


		connection.sendIQ(iq.tree(), function() { alert('success'); }, function(err) { console.log('error', err); });
        
    });
 
 	//获取组群成员
    $('#btn-getgroupuser').click(function() {
    	if(connected) {

    		
        } else {
            alert("请先登录！");
        }
    });
 	//发送组群共享文件
    $("#btn-sendfile").click(function() {
        if(connected) {

        	//先自行上传文件，将路径记录下来,查看文件时需要程序下载
        	var fpath = '/201908/skdljfiowwewffjjw.docx';
            // 创建一个<message>元素并发送
            var msg = $msg({
                to: $("#input-groupjid").val() + GROUP_DOMAIN, 
                from: jid, 
                type: 'groupchat'
            }).c("body", null, 'fileType=<DOC>|fileName=<抗衰老的房间.docx>|path=<' + fpath + '>');
            connection.send(msg.tree());

            $("#input-msg").val('');
        } else {
            alert("请先登录！");
        }
    });
 	
  //后台增加组群用户
    $('#btn-addgroupuserback').click(function() {
    	alert('11');
    	 $.post("<%=request.getContextPath()%>/talk.do?action=initTalkGroupUser",
    			  {
    			    name:"Donald Duck",
    			    city:"Duckburg"
    			  },
    			  function(data,status){
    			    alert("Data: " + data + "\nStatus: " + status);
    			  });
    });
  //后台发送主题消息
    $('#btn-sendgroupmsgback').click(function() {
    	alert('12');
    	 $.post("<%=request.getContextPath()%>/talk.do?action=sendTalkGroupMsg",
    			  {
    			    message:$("#input-msg").val(),
    			    //idTalkUser:$("#input-jid").val(),
    			    idGroup:$("#input-groupjid").val()
    			  },
    			  function(data,status){
    			    alert("Data: " + data + "\nStatus: " + status);
    			  });
    });
  
  //后台给登录用户发送消息
    $('#btn-sendusermsgback').click(function() {
    	alert('12');
    	 $.post("<%=request.getContextPath()%>/talk.do?action=sendTalkUserMsg",
    			  {
    			    message:$("#input-msg").val(),
    			    idTalkUser:$("#input-jid").val(),
    			    idGroup:$("#input-groupjid").val()
    			  },
    			  function(data,status){
    			    alert("Data: " + data + "\nStatus: " + status);
    			  });
    });
  //后台加入组群
    $('#btn-joingroupback').click(function() {
    	alert('13');
    	 $.post("<%=request.getContextPath()%>/talk.do?action=joinTalkGroup",
    			  {
    			    idUser:$("#input-jid").val(),
    			    idGroup:$("#input-groupjid").val()
    			  },
    			  function(data,status){
    			    alert("Data: " + data + "\nStatus: " + status);
    			  });
    });
  
  //获取我的组群
    $('#btn-getmygroup').click(function() {
    	alert('14');
    	 $.post("<%=request.getContextPath()%>/talk.do?action=getMyTalkGroups",
    			  {
    		 		idTalkUser:$("#input-jid").val()
    			  },
    			  function(data,status){
    				  console.log(data);
    			    alert("Data: " + data + "\nStatus: " + status);
    			  });
    });
  
    //获取我的站内信(消息)</button>
    $('#btn-getmymsgs').click(function() {
    	alert('15');
    	 $.post("<%=request.getContextPath()%>/talk.do?action=getMyTalkMsgs",
    			  {
    		 		idTalkUser:$("#input-jid").val(),
    		 		start:0,
    		 		limit:100
    		 		
    			  },
    			  function(data,status){
    				  console.log(data);
    			    alert("Data: " + data + "\nStatus: " + status);
    			  });
    });
    
    //获取业务(消息)</button>
    $('#btn-getbusinessmsgs').click(function() {
    	alert('16');
    	 $.post("<%=request.getContextPath()%>/talk.do?action=getTalkBusinessMsgs",
    			  {
    		 		idBusiness:'6675b3f42d07482cbe34329de71622b3',
    		 		idBusinessType:'PROJECT_DAILY_REPORT',
    		 		start:0,
    		 		limit:10000,
    		 		filteredOutNids:'28',
    		 		keyword:$("#input-msg").val()

    			  },
    			  function(data,status){
    				  console.log(data);
    			    alert("Data: " + data + "\nStatus: " + status);
    			  });
    });
  
});
</script>
</html>